package com.qiche.controller.mgr;

import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.qiche.aspect.Result;
import com.qiche.common.TokenCache;
import com.qiche.dto.RegisterDto;
import com.qiche.model.Merchant;
import com.qiche.model.User;
import com.qiche.redis.RedisService;
import com.qiche.service.MerchantService;
import com.qiche.service.UserService;
import com.qiche.util.AliyunSmsUtils;
import com.qiche.util.MathUtis;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 注册管理控制器
 */
@Api(value = "/registers",description = "注册管理控制器")
@RestController
@RequestMapping("/registers")
public class RegisterController {
    @Resource
    private UserService userService;
    @Resource
    private MerchantService merchantService;
    @Resource
    private RedisService redisService;

    @ApiOperation(value ="表单提交注册" )
    @PostMapping(value = "/register")
    public Result<User> toRegister(@Validated RegisterDto dto, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return Result.createByErrorMessage(bindingResult.getFieldError().getDefaultMessage());
        }
        return userService.register(dto);
    }

    @ApiOperation(value ="注册验证用户名合法性")
    @PostMapping(value = "/isUsernameValid")
    public Map<String, Object> isUsernameValid(String username) {
        Map<String, Object> map = new HashMap<>();
        boolean exist = userService.isUsernameExist(username);
        if (!exist) {
            map.put("code", 500);
            map.put("msg", "用户名不存在");
            return map;
        }
        //用户名合法性通过时 带出其手机号用于发短信
        String phone = "";
        User user = userService.selectByUsername(username);
        if (StringUtils.isBlank(user.getPhone())) {
            //找门店关联手机号
            Merchant merchant = merchantService.selectById(user.getMerchantId().longValue());
            if (merchant != null) {
                phone = merchant.getPhone();
            }
        } else {
            phone = user.getPhone();
        }
        map.put("code", 2000);
        map.put("msg", "success");
        map.put("username", username);
        map.put("phone", phone);
        return map;
    }

    @ApiOperation(value ="忘记密码的验证码校验")
    @PostMapping(value = "/checkVerifyCode.do")
    public Result<String> checkVerifyCode(String username, String vcodes) {
        return userService.forgetCheckVerifyCode(username, vcodes);
    }

    @ApiOperation(value ="忘记密码的重置密码")
    @PostMapping(value = "/resetPassWord.do")
    public Result<String> resetPassWord(String username, String newPassword, String forgetToken) {
        return userService.forgetResetPassword(username, newPassword, forgetToken);
    }

    @ApiOperation(value ="发送验证码(来源：1注册验证码 2：忘记密码验证码)")
    @PostMapping(value = "/sendVerifyCode")
    public Map<String, Object> sendVerifyCode(Integer manner, String phone, String username) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String toSendPhone = "";
        String verifyCode = MathUtis.getRandomString(6);
        SendSmsResponse resp = null;
        if (manner == 1) {
            resp = AliyunSmsUtils.sendSms(phone, verifyCode);
        } else {
            // 两种方式：1.取用户的手机号 2.要根据用户名找到门店预留手机号码
            User user = userService.selectByUsername(username);
            if (StringUtils.isBlank(user.getPhone())) {
                Merchant merchant = merchantService.selectById(user.getMerchantId().longValue());
                toSendPhone = merchant.getPhone();
            } else {
                toSendPhone = user.getPhone();
            }
            resp = AliyunSmsUtils.sendSms(toSendPhone, verifyCode);
        }
        if (StringUtils.isNotBlank(resp.getCode()) && resp.getCode().equals("OK")) {
            if (manner == 1) {
                redisService.set(phone + "registerVerifyCode", verifyCode, 300L);
                //redisManager.set(phone + "registerVerifyCode", verifyCode, 60 * 5);
                map.put("status", 1);
            } else if (manner == 2) {
                //加载缓存
                String forgetToken = UUID.randomUUID().toString();
                TokenCache.setKey(TokenCache.TOKEN_PREFIX + username, forgetToken);
                redisService.set(toSendPhone + "forgetPasswordVerifyCode", verifyCode, 300L);
             //   redisManager.set(toSendPhone + "forgetPasswordVerifyCode", verifyCode, 60 * 5);
                map.put("status", 1);
                map.put("forget_token", forgetToken);
            }
        } else {
            map.put("status", 0);
        }
        return map;
    }

}
